import Vue from 'vue'
import Router from 'vue-router'
import nprogress from 'nprogress'
import constantRouterMap from './constantRouterMap'
import config from '@/config'
import token from '@/utils/token'
import * as tools from '@/utils/tools'
import 'nprogress/nprogress.css'

Vue.use(Router)

//  const originalPush = Router.prototype.push
//  Router.prototype.push = function push(location) {
//      return originalPush.call(this, location).catch(err => err)
//  }


let routes = constantRouterMap

let router = new Router({
    mode: 'history',
    base: config.publicPath,
    routes: routes,
    scrollBehavior: (to, from, savedPosition) => {
        if (savedPosition) {
            return savedPosition
        } else {
            if (from.meta.keepAlive) {
                from.meta.savedPosition = document.body.scrollTop
            }
            return {
                x: 0,
                y: to.meta.savedPosition || 0
            }
        }
    }
})


router.beforeEach((to, from, next) => {
    nprogress.start()
    if (to.path === '/login') {
        next()
    } else if (token.get()) {
        if (!tools.checkRouter()) {
            tools.initRouter().then(res => {
                next({path: to.path})
            })
        } else {
            next()
        }
    } else {
        next('/login')
        nprogress.done() //  如果当前页是 login 则路由不会触发 after 钩子函数，需要手动处理
    }


})

router.afterEach(to => {
    nprogress.done()
})

export default router
